// Load modules.
var OAuth2Strategy = require("passport-oauth2");
var querystring = require("querystring");
var util = require("util");
var crypto = require("crypto");
var urllib = require("urllib");

function ensureToken(oauthIns) {
    var params = {
        appid: oauthIns._clientId,
        app_secret: oauthIns._clientSecret
    }
    var _ensure = function () {
        oauthIns._request('GET', oauthIns._getAccessTokenUrl() + '?' + querystring.stringify(params), {
            "Content-Type": "application/json"
        }, null, null, function (err, data, res) {
            if (err) throw err
            data = JSON.parse(data)
            console.log(data);
            if (data && data.access_token) {
                oauthIns.access_token = data.access_token
                setTimeout(_ensure,  7100 * 1000)
            } else {
                setTimeout(_ensure, 2000)
            }
        })
    }
    _ensure()
}

function Strategy(options, verify) {
    options = options || {};
    options.authorizationURL =
        options.authorizationURL || `https://auth.uupt.work/passport/authorize?appid=${options.clientID}`;
    options.callbackURL = options.callbackURL ||  `${options.host}/auth/uuoa/callback`;
    options.scopeSeparator = options.scopeSeparator || ",";
    options.tokenURL = options.tokenURL || "https://api.uupt.work/open/auth/token";
    OAuth2Strategy.call(this, options, verify);
    this.name = "uuoa";
    this._oauth2._userProfileURL = options.userProfileURL || "https://api.uupt.work/open/auth/user_info";
    this._oauth2._persistentTokenURL = options.persistentTokenURL || "https://api.uupt.work/open/auth/access_token";
    this._host = options.host;
    ensureToken(this._oauth2)
    this._oauth2.getOAuthAccessToken = function (code, params, callback) {
        var self = this;
        urllib.request(
            this._persistentTokenURL,
            {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + self.access_token,
                },
                method: "GET",
                dataType: "json",
                data: {
                    code: code,
                    grant_type: "authorization_code"
                }
            },
            function (err, data, res) {
                if (err) return callback(err);
                var accessToken = data.access_token;
                if (!accessToken)
                    return callback(new Error("refreshToken failed"));
                callback(null, accessToken, data.union_id, data); // callback results =-=
            }
        );
    };
}

// Inherit from `OAuth2Strategy`.
util.inherits(Strategy, OAuth2Strategy);

OAuth2Strategy.prototype._loadUserProfile = function (
    accessToken,
    done,
    params
) {
    let accessTokenArr = accessToken.split('_');
    this.userProfile(accessTokenArr, done, accessTokenArr[1] || '');
};
Strategy.prototype.authorizationParams = function (params) {
    // 构建提交参数
    params = params || {};
    console.log(params)
    params["response_type"] = "code";
    return params;
};
Strategy.prototype.userProfile = function (accessToken, done, cropId) {
    urllib.request(
        this._oauth2._userProfileURL,
        {
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + accessToken,
            },
            method: "GET",
            dataType: "json"
        },
        function (err, data, res) {
            console.log(data, '打印返回信息')
            return done(null, {
                provider: "uuoa",
                id: data.ding_id,
                name: data.name,
                cropId: data.corp.corp_code,
                corpIcon: data.corp.icon_url,
                privateId: data.ding_unionid,
                mobile: data.mobile,
                email: data.email, //官方缺少email字段，待修复
                headurl: data.avatar,
                _json: data
            });
        }
    );
};

// Expose constructor.
module.exports = Strategy;